package com.sghd.fight;

import com.sghd.common.console.Console;
import com.sghd.common.console.ConsoleProgressBar;
import com.sghd.common.socket.handler.filter.firewall.FirewallFilter;
import com.sghd.common.socket.session.Session;
import com.sghd.common.socket.session.SessionManager;
import com.sghd.fight.module.game.service.GameService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

/**
 * @author wch
 * @date 2018-10-17 14:00
 * @desc
 **/
public class App {
    private static final Logger logger = LoggerFactory.getLogger(App.class);
    /** 默认的上下文配置名 */
    private static final String DEFAULT_APPLICATION_CONTEXT = "applicationContext.xml";

    public static void main(String[] arguments) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        final ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(DEFAULT_APPLICATION_CONTEXT);
        try {
            logger.debug("游戏服容器已启动完成，开启服务器控制台");
            Console console = new DefinConsole(applicationContext);
            console.start();
        } catch (Exception exception) {
            exception.printStackTrace();
            if (applicationContext.isRunning()) {
                applicationContext.destroy();
            }
        }
    }

    public static final void saveProcessId() {
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        Integer processId = Integer.valueOf(runtimeMXBean.getName().split("@")[0]);
        try {
            File file = new File("pid");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(processId + "");
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            logger.error("PID[{}]文件生成失败！", processId, e);
        }
    }

    public static class DefinConsole extends Console {
        private SessionManager sessionManager;
        private FirewallFilter firewallFilter;
        private GameService gameService;

        public DefinConsole(AbstractApplicationContext applicationContext) {
            super(applicationContext);
            this.sessionManager = applicationContext.getBean(SessionManager.class);
            this.firewallFilter = applicationContext.getBean(FirewallFilter.class);
            this.gameService = applicationContext.getBean(GameService.class);
        }

        @Override
        public void stop() {
            //禁止所有玩家登陆
            firewallFilter.blockAll();
            //强制结算
            logger.debug("强制结算在线玩家！");
            gameService.stop();
            //踢除所有玩家下线
            sessionManager.kickAll(Session.KICK);
            ConsoleProgressBar console = new ConsoleProgressBar();
            for (int i = 1; i <= 100; i++) {
                float rate = (float) (i * 1.0 / 100);
                console.print("Progress: # " + console.format(rate));
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
            console.nextLine();
            super.stop();
        }
    }
}
